#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "msgbus_lib.h"
#include "hdb_lib.h"
#include "sample_his_define.h"
#include "sqlite3_interface.h"

#define SQLITE3_DATABASE_FILE "/users/oracle/cl8000/save/sqlite_hist_sample.db"	//定义SQLite3数据库文件的路径

extern duplicat_info sample_dup_info;


sqlite3_interface::sqlite3_interface()
{
	pdbfile = (char *)malloc(sizeof(SQLITE3_DATABASE_FILE)+1);
	strcpy(pdbfile,SQLITE3_DATABASE_FILE);
	ppDb = NULL;
	cur_len = 0;
	sql_buf[0] = 0;
}

sqlite3_interface::~sqlite3_interface()
{
	free(pdbfile);
	free(ppDb);
	pdbfile = NULL;
	ppDb = NULL;
	cur_len = 0;
	sql_buf[0] = 0;
}

int sqlite3_interface::open_database()
{
	int ret = -1;
	ret = sqlite3_open(pdbfile, &ppDb);
	if (ret){
		printf("Can't open database: %s\n", sqlite3_errmsg(ppDb));
	}else{
		printf("Open database successfully\n");
	}
	return ret;
}

int sqlite3_interface::close_database()
{
	int ret = -1;
	ret = sqlite3_close(ppDb);
	if (ret){
		printf("Close database failure: %s\n");
	}else{
		printf("Close database successfully\n");
	}
	return ret;
}

int sqlite3_interface::add_one_sql_sentence(char *sql_sen,int type)
{
	int	len,ret=0;
	len = strlen(sql_sen);
	if (len + cur_len >= HIST_SAM_MAX_SENTENCE_BUF_LEN-2)
		if(execute_all_sql(type))
		{
			printf("Execute_all_sql failure: %s\n");
			ret = -1;
		}	
	strcat(sql_buf,sql_sen);
	strcat(sql_buf,"\n");
	cur_len = strlen(sql_buf);
	return ret;
}

int sqlite3_interface::execute_all_sql(int type)
{
	int ret = -1;
	if (cur_len <= 0)
	return ret;

	if (type == SAMPLE_HIST_YC)
		ret = ExecuteSqlSentence8(sql_buf);
	else
		ret = ExecuteSqlSentence9(sql_buf);

	cur_len =0;
	sql_buf[0] = 0;
	
	return ret;
}

int sqlite3_interface::ExecuteSqlSentence8(char *sql_sentence)
{
	int ret,i,j,len;
	char *errmsg;

    sample_dup_info.save_one_report(DUPLICAT_SEND,
            DUPLICAT_SQL_SETTENCE,
            strlen(sql_sentence)+1,
            sql_sentence);

	len = strlen(sql_sentence);
	j = 0;
	for (;j<len;)
	{
		for (i=j+1;i<len;i++)
		if (sql_sentence[i] == '\n' ||
			sql_sentence[i] == 0)
		{
			sql_sentence[i] = 0;
			break;
		}
	
		ret = sqlite3_exec(ppDb, sql_sentence+j, NULL, NULL, &errmsg);
		if (ret)
		{ 
			printf("SQL Sentence8 error: %s\n", errmsg);
			sqlite3_free(errmsg);
		}
		j = i+1;
	}
	return ret;
}

int sqlite3_interface::ExecuteSqlSentence9(char *sql_sentence)
{
	int ret,i,j,len,num=0;
	char *errmsg;

	ret = -1;
	len = strlen(sql_sentence);
	j = 0;
	for (;j<len;)
	{
		for (i=j+1;i<len;i++)
		if (sql_sentence[i] == '\n' ||
			sql_sentence[i] == 0)
		{
			sql_sentence[i] = 0;
			break;
		}
		num ++;
		ret = sqlite3_exec(ppDb, sql_sentence+j, NULL, NULL, &errmsg);
		if (ret)
		{ 
			fprintf(stderr, "SQL Sentence9 error: %s\n", errmsg);
			sqlite3_free(errmsg);
		}
		j = i+1;
		if(num%100==0) usleep(1000);
	}
	return ret;
}


